package plenprojects.security;

import plenprojects.dao.ChatServiceDao;
import plenprojects.exceptions.AuthenticationException;
import plenprojects.model.UserDetails;

public class LoginAuthenticator {
	
	private PasswordEncoder encoder;
	private ChatServiceDao dao;
	
	public void authenticate(String username, String password) throws AuthenticationException {
		
		if(username == null || password == null) {
			
			throw new AuthenticationException("Username or password not set.");
		}
		
		UserDetails details = dao.getDetailsFromUsername(username);
		
		if(details == null) {
			
			throw new AuthenticationException("No such user.");
		}
		
		String hash = encoder.encode(password);
		
		if(!hash.equals(details.getHash())) {
			
			throw new AuthenticationException("Incorrect password.");
		}
	}
	
	public void setEncoder(PasswordEncoder encoder) {
		
		this.encoder = encoder;
	}

	public void setDao(ChatServiceDao dao) {
		
		this.dao = dao;
	}
	
}
